﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using digit.Core;
using SMS.ServiceManager;
using SMS.UserManager;

namespace SMS.Admin.Modules
{
    public partial class DetailPlayer : WebControlBase
    {
        protected bool _display = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            PlayerID = Request.QueryString["playerId"] != null ? Int32.Parse(Request.QueryString["playerId"].ToString().Trim()) : -1;

            if (ClientState.MemberInfo.UserType != 0 && ClientState.MemberInfo.UserType != 1)
            {
                if (PlayerID == -1)
                {
                    lnkSave.Enabled = false;
                }
            }

            if (this.IsPostBack) return;

            if (PlayerID > 0)
            {
                this.BindObject();
            }
        }

        protected void lnkCancel_Click(object sender, System.EventArgs e)
        {
            Response.Redirect("Default.aspx?module=ListPlayer");
        }

        private void BindObject()
        {
            PlayerInfo objPlayer = PlayerManager.Select(PlayerID);

            if (objPlayer != null)
            {
                this.txtPlayerName.Text = objPlayer.PlayerName;
                this.txtInfo.Text = objPlayer.Info;
                this.lblCreater.Text = objPlayer.CreatedBy;
                this.lblCreateDate.Text = objPlayer.CreatedDate.ToString("dd/MM/yyyy");
                this.txtArchive.Text = objPlayer.Archieve;
                this.txtHeight.Text = objPlayer.Height;
                this.txtWeight.Text = objPlayer.Weight;
                this.txtPosition.Text = objPlayer.PlayPosition;
                this.txtShirtNo.Text = objPlayer.ShirtNo;
                this.txtPastTeam.Text = objPlayer.PastTeam;
                this.txtBirthday.Text = objPlayer.Birthday;
                this.txtBirthPlace.Text = objPlayer.BirthPlace;
                FileUploadPath = objPlayer.ImgPath;

                if (objPlayer.Status == 1)
                    chkStatus.Checked = true;
            }
        }

        private long DoSave()
        {
            try
            {
                bool result = false;
                if (PlayerID > 0)
                {
                    PlayerInfo objPlayer = PlayerManager.Select(PlayerID);
                    if (objPlayer != null)
                    {
                        byte bytStat = 2;
                        if (chkStatus.Checked == true)
                            bytStat = 1;

                        result = PlayerManager.Update(PlayerID, txtPlayerName.Text, txtBirthday.Text, txtWeight.Text, txtHeight.Text, txtShirtNo.Text, txtPosition.Text, FileUploadPath, txtBirthPlace.Text, txtArchive.Text, txtPastTeam.Text, "", "", txtInfo.Text, "admin", DateTime.Now, 1, bytStat);
                    }
                }
                else
                {
                    PlayerInfo objPlayer = new PlayerInfo();
                    if (objPlayer != null)
                    {
                        objPlayer.PlayerName = this.txtPlayerName.Text.Trim();
                        objPlayer.Info = txtInfo.Text;
                        objPlayer.CreatedDate = DateTime.Now;
                        objPlayer.Height = txtHeight.Text;
                        objPlayer.Weight = txtWeight.Text;
                        objPlayer.PlayPosition = txtPosition.Text;
                        objPlayer.BirthPlace = txtBirthPlace.Text;
                        objPlayer.Birthday = txtBirthday.Text;
                        objPlayer.Archieve = txtArchive.Text;
                        objPlayer.PastTeam = txtPastTeam.Text;
                        objPlayer.ShirtNo = txtShirtNo.Text;

                        if (Session["UserName"] != null)
                            objPlayer.CreatedBy = ClientState.MemberInfo.Username;
                        else
                            objPlayer.CreatedBy = "";

                        objPlayer.ImgPath = FileUploadPath;

                        if (Session["UserName"] != null)
                            objPlayer.CreatedBy = ClientState.MemberInfo.Username;
                        else
                            objPlayer.CreatedBy = "";

                        objPlayer.Status = 2;

                        result = PlayerManager.Insert(objPlayer);
                        if (result)
                            lblError.Text = "Cập nhật thành công!";

                        return 0;
                    }
                }
                return 0;
            }
            catch { return -1; }
        }

        private void UploadImg(FileUpload updUploadFile, out string strFileOutputPath, Label lblErr)
        {
            strFileOutputPath = "";
            try
            {
                string strRelatePath = "Assets/Player/";
                string strRootPath = Util.GetAppSettings("MediaFolder");

                //Create directory
                string dir_name = DateTime.Now.ToString("ddMMyyyy");
                if (System.IO.Directory.Exists(dir_name)) { }
                else
                    Directory.CreateDirectory(strRootPath + strRelatePath + dir_name);

                //Fix the relative path to physical path to upload
                string strFilePath = strRootPath + strRelatePath + dir_name + "/" + updUploadFile.FileName;

                string strExt = Path.GetExtension(updUploadFile.PostedFile.FileName).ToLower().Replace(".", "");

                if ((strExt == "jpg") || (strExt == "png") || (strExt == "gif") || (strExt == "flv") || (strExt == "swf") || (strExt == "wmv"))
                {
                    //If not exist a file then load this file
                    if (!File.Exists(strFilePath))
                    {
                        //System.Drawing.Image imgUpload = Bitmap.FromStream(updUploadFile.PostedFile.InputStream);
                        //imgUpload.Save(strFilePath, imgUpload.RawFormat);

                        updUploadFile.PostedFile.SaveAs(strFilePath);

                        strFileOutputPath = strRelatePath + dir_name + "/" + Path.GetFileNameWithoutExtension(updUploadFile.PostedFile.FileName) + Path.GetExtension(updUploadFile.PostedFile.FileName).ToLower();

                        lblErr.Text = "File <" + updUploadFile.FileName + "> upload thành công!";
                    }

                    //If existed or save process has error then alert message
                    else
                    {
                        lblErr.Text = "File <" + updUploadFile.FileName + "> đã tồn tại, vui lòng đổi tên!";
                    }
                }
                else
                {
                    lblErr.Text = "Bạn không được phép upload file này!";
                }
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }

        protected void lbtnUploadImg_Click(object sender, System.EventArgs e)
        {
            //Upload large image
            string OutString = "";
            UploadImg(uplImgPath, out OutString, lblImg);
            FileUploadPath = OutString;
        }

        protected void lnkSave_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                if (DoSave() != -1)
                    this.lblError.Text = "Cập nhật thành công!";
                else
                    this.lblError.Text = PlayerManager.ErrorMessage;
            }
            else
            {
                this.lblError.Text = "Bạn chưa nhập đầy đủ các thông tin cần thiết hoặc nhập sai, hãy kiểm tra lại";
            }
        }

        private long PlayerID
        {
            get
            {
                if (this.ViewState["vsPlayerID"] != null)
                    return (long)this.ViewState["vsPlayerID"];
                else
                    return -1;
            }

            set { this.ViewState["vsPlayerID"] = value; }
        }

        protected string FileUploadPath
        {
            get
            {
                if (this.ViewState["vsFileUploadPath"] != null)
                    return (string)this.ViewState["vsFileUploadPath"];
                else
                    return "";
            }

            set
            {
                this.ViewState["vsFileUploadPath"] = value;
            }
        }
    }
}
